<?php
/**
 * A logger class which creates logs when an exception is thrown.
 * 
 * @package appublisher
 * @subpackage Logger
 * @author bluer
 * @version 0.2
 */

/**
 * Define log directory name
 * 
 * Absolute and DocumentRoot-relative paths supported. Default is DocumentRoot-relative path.
 */
if (!defined('LOG_DIR')) define('LOG_DIR', 'logs/');
if (!defined('LOG_FILENAME')) define('LOG_FILENAME', 'debug.log');

class Logger {
    /**
     * Log directory Path
     *
     * @access private
     * @var string
     */
    private static $_path;
    
    /**
     * A file pointer resource
     *
     * @access private
     * @var resource
     */
    private static $_fp = null;
    
    /**
     * Logger instance
     *
     * @access private
     * @var object
     */
    private static $_instance; 
	
    public function __construct() {
        date_default_timezone_set('Asia/Shanghai');
		
        if (substr(LOG_DIR, 0, 1)==='/') {
            self::$_path = LOG_DIR;
        } else {
            self::$_path = $_SERVER['DOCUMENT_ROOT']. '/' . LOG_DIR;
        }
        
        if (is_null(self::$_fp))  self::init();
    }
    
    public function __destruct() {
        if ( is_resource(self::$_fp) )  {
            fclose(self::$_fp);
            self::$_fp = null;
        }
        
        return true;
    }
    
    /**
     * Init and open the log file
     *
     */
    private static function init() {
        if (self::checkDir()) {
            $filepath = self::$_path . LOG_FILENAME;
            self::$_fp = fopen($filepath, 'a+') or die("Fatal Error: failed to create $filepath");
        }
    }
	
    /**
     * Checks if directory exists
     *
     * @access private
     * 
     * @return bool
     */
    private static function checkDir() {
        if (!is_dir(self::$_path) && mkdir(self::$_path, 0777)===false) {
            return false;
        }
        
        return true;
    }
	
    /**
     * Logs the massage
     *
     * @param string $message	The message which is written into the log
     * @param string $level		Log levels
     */
    private static function _write($message, $level = 'INFO') {
        if (is_null(self::$_fp) || is_null(self::$_instance)) {
            self::$_instance = new Logger();
        }
        
        if (is_resource(self::$_fp)) {
            $log = sprintf("%s [%s]#%s: %s\n", date('d/M/Y:H:i:s O'), $level,  getmygid(), trim($message));
            fwrite(self::$_fp, $log);
        }
    }
    
    /**
     * Message type: Error
     *
     * @param string $message	The message which is written into the log
     */
    public static function e($message) {
        self::_write($message, 'ERROR');
    }
    
    /**
     * Message type: Info
     *
     * @param string $message	The message which is written into the log
     */
    public static function i($message) {
        self::_write($message);
    }
}
?>